package org.linlinjava.litemall.wx.service.impl;

import org.linlinjava.litemall.db.dao.LitemallMessageMapper;
import org.linlinjava.litemall.db.dao.LitemallUserMapper;
import org.linlinjava.litemall.db.domain.LitemallMessage;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.linlinjava.litemall.wx.service.WxMessageService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import com.alibaba.fastjson.JSON;
import org.linlinjava.litemall.wx.config.WebSocketServer;
import java.util.Date;
import org.linlinjava.litemall.db.dao.LitemallChatSessionMapper;
import org.linlinjava.litemall.db.domain.LitemallChatSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class WxMessageServiceImpl implements WxMessageService {
    @Resource
    private LitemallMessageMapper messageMapper;

    @Resource
    private LitemallChatSessionMapper chatSessionMapper;

    @Resource
    private LitemallUserMapper userMapper;

    private static final Logger logger = LoggerFactory.getLogger(WxMessageServiceImpl.class);

    @Override
    @Transactional
    public int sendMessage(LitemallMessage message) {
        try {
            // 设置消息基本信息
            message.setCreateTime(new Date());
            message.setRead(false);

            // 1. 保存消息到数据库
            int result = messageMapper.insert(message);

            if (result > 0) {
                // 2. 更新或创建会话
                updateChatSession(message);

                // 3. 尝试实时推送消息
                String wsMessage = JSON.toJSONString(message);
                boolean delivered = WebSocketServer.sendMessage(message.getReceiverId(), wsMessage);

                // 4. 更新未读消息计数（仅当用户不在线或推送失败时）
                if (!delivered) {
                    chatSessionMapper.increaseUnreadCount(
                            message.getReceiverId(),
                            message.getSenderId()
                    );
                }

                // 5. 发送成功的响应
                logger.info("消息发送成功 - 消息ID: {}, 接收者: {}, 实时推送状态: {}",
                        message.getId(), message.getReceiverId(), delivered ? "成功" : "待推送");

                return result;
            }

            return 0;
        } catch (Exception e) {
            logger.error("发送消息失败: ", e);
            throw new RuntimeException("发送消息失败: " + e.getMessage());
        }
    }

    /**
     * 更新聊天会话
     */
    private void updateChatSession(LitemallMessage message) {
        // 1. 为发送者创建/更新会话记录
        LitemallChatSession senderSession = new LitemallChatSession();
        senderSession.setUserId(message.getSenderId());      // 发送者的会话
        senderSession.setPartnerId(message.getReceiverId()); // 对话对象是接收者
        senderSession.setLastMessage(message.getContent());
        senderSession.setLastSenderId(message.getSenderId()); // 记录最后消息发送者
        senderSession.setProductId(message.getProductId());
        senderSession.setCreateTime(LocalDateTime.now());
        senderSession.setUpdateTime(LocalDateTime.now());
        senderSession.setUnreadCount(0); // 发送者不需要未读计数
        
        // 获取接收者信息作为发送者会话的对象信息
        setPartnerInfo(senderSession, message.getReceiverId());
        chatSessionMapper.insertOrUpdate(senderSession);

        // 2. 为接收者创建/更新会话记录  
        LitemallChatSession receiverSession = new LitemallChatSession();
        receiverSession.setUserId(message.getReceiverId());   // 接收者的会话
        receiverSession.setPartnerId(message.getSenderId());  // 对话对象是发送者
        receiverSession.setLastMessage(message.getContent());
        receiverSession.setLastSenderId(message.getSenderId()); // 记录最后消息发送者
        receiverSession.setProductId(message.getProductId());
        receiverSession.setCreateTime(LocalDateTime.now());
        receiverSession.setUpdateTime(LocalDateTime.now());
        receiverSession.setUnreadCount(1); // 接收者需要未读计数
        
        // 获取发送者信息作为接收者会话的对象信息
        setPartnerInfo(receiverSession, message.getSenderId());
        chatSessionMapper.insertOrUpdate(receiverSession);
    }

    /**
     * 设置聊天对象信息
     */
    private void setPartnerInfo(LitemallChatSession session, String partnerId) {
        try {
            Integer userId = Integer.valueOf(partnerId);
            LitemallUser user = userMapper.selectByPrimaryKey(userId);
            if (user != null) {
                session.setPartnerName(user.getNickname());
                session.setPartnerAvatar(user.getAvatar());
            } else {
                session.setPartnerName("访客" + partnerId);
                session.setPartnerAvatar("/static/images/default-avatar.png");
            }
        } catch (Exception e) {
            session.setPartnerName("访客" + partnerId);
            session.setPartnerAvatar("/static/images/default-avatar.png");
        }
    }

    @Override
    public List<LitemallMessage> getMessageList(String userId, String partnerId, Integer offset, Integer limit,Integer productId) {
//        logger.info("执行消息查询: userId={} partnerId={} offset={} limit={}",
//            userId, partnerId, offset, limit);
        
        List<LitemallMessage> messages = messageMapper.selectList(userId, partnerId, offset, limit,productId);
        logger.info("查询到 {} 条消息记录", messages.size());
        
        return messages;
    }

    @Override
    public List<LitemallChatSession> getChatList(String userId) {
        logger.info("开始查询用户 {} 的聊天列表", userId);
        List<LitemallChatSession> chatList = chatSessionMapper.selectByUserId(userId);
        
        // 添加调试日志
        logger.debug("原始查询结果：");
        for (LitemallChatSession session : chatList) {
            logger.debug("会话详情：{}", session.toString());
        }
        
        return chatList;
    }

    @Override
    @Transactional
    public int markMessageRead(String userId, String partnerId) {
        return messageMapper.markRead(userId, partnerId);
    }

    @Override
    public int getUnreadCount(String userId, String partnerId) {
        return messageMapper.countUnread(userId, partnerId);
    }

    @Override
    @Transactional
    public void createChat(LitemallChatSession chatSession, LitemallMessage message) {
        // 创建或更新会话
        chatSessionMapper.insertOrUpdate(chatSession);
        
        // 保存系统消息
        messageMapper.insert(message);
    }
}